#!/usr/bin/env bash
#================ =================================
#	System Required: CentOS/
#	Description:一个综合shell脚本
#	Version: xxxx
#	Author: baibaibai
#	gitee: http://gitee.com/baibaibai001/shell
#=================================================
var1="1.自动配置yum"
var2="2.系统监控"
var3="3.程序安装"
var4="4.系统管理（调优）"
var5="5.一键部署"
var99="99.检查脚本更新"
ask="请输入你要选择功能（0返回）："
error_ask="你输入了错误的指令，请重新输入！"
shell_address=http://gitee.com/baibaibai001/shell
shell_log=
#每次提交需要 修改本地版本号需要于GitHub的version一致
Script_version="20220115"
＃字体颜色
blue(){
    echo -e "\033[34m\033[01m$1\033[0m"
}
green(){
    echo -e "\033[32m\033[01m$1\033[0m"
}
red(){
    echo -e "\033[31m\033[01m$1\033[0m"
}
#检查系统判断apt-get|yum
check_sys(){
	if [[ -f /etc/redhat-release ]]; then
		release="centos"
	elif cat /etc/issue | grep -q -E -i "debian"; then
		release="debian"
	elif cat /etc/issue | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
	elif cat /proc/version | grep -q -E -i "debian"; then
		release="debian"
	elif cat /proc/version | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
    fi
	bit=$(uname -m)
	echo "$release $bit"
}


#2.系统监控

get_system_info(){
  # 获取系统cpu信息
function get_cpu_info() {
    Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
    Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
    CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
    CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
    CPU_Arch=$(uname -m)
cat <<EOF
CPU信息:
物理CPU个数:$Physical_CPUs
逻辑CPU个数:$Virt_CPUs
每CPU核心数:$CPU_Kernels
CPU型号:$CPU_Type
CPU架构:$CPU_Arch
EOF
}
#-----end---------
# 获取系统内存信息
function get_mem_info() {
    check_mem=$(free -m)
    MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}')  #KB
    MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}')    #KB
    let MemUsed=MemTotal-MemFree
    MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")
    report_MemTotal="$((MemTotal/1024))""MB"        #内存总容量(MB)
    report_MemFree="$((MemFree/1024))""MB"          #内存剩余(MB)
    report_MemUsedPercent="$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")""%"   #内存使用率%

cat <<EOF
内存信息：
${check_mem}
EOF
}
#--------end------------

# 获取系统网络信息
function get_net_info() {
    pri_ipadd=$(ip a show dev eth0|grep -w inet|awk '{print $2}'|awk -F '/' '{print $1}')
    pub_ipadd=$(curl ifconfig.me -s)
    gateway=$(ip route | grep default | awk '{print $3}')
    mac_info=$(ip link| egrep -v "lo"|grep link|awk '{print $2}')
    dns_config=$(egrep -v "^$|^#" /etc/resolv.conf)
    route_info=$(route -n)
cat <<EOF
IP信息:
系统公网地址:${pub_ipadd}
系统私网地址:${pri_ipadd}
网关地址:${gateway}
MAC地址:${mac_info}
路由信息:
${route_info}
DNS 信息:
${dns_config}
EOF
}
#------end----------

# 获取系统磁盘信息
function get_disk_info() {
    disk_info=$(fdisk -l|grep "Disk /dev"|cut -d, -f1)
    disk_use=$(df -hTP|awk '$2!="tmpfs"{print}')
    disk_inode=$(df -hiP|awk '$1!="tmpfs"{print}')

cat <<EOF
磁盘信息:
${disk_info}
磁盘使用:
${disk_use}
inode信息:
${disk_inode}
EOF
}
#--------end--------------
# 获取系统磁盘信息
function get_disk_info() {
    disk_info=$(fdisk -l|grep "Disk /dev"|cut -d, -f1)
    disk_use=$(df -hTP|awk '$2!="tmpfs"{print}')
    disk_inode=$(df -hiP|awk '$1!="tmpfs"{print}')

cat <<EOF
磁盘信息:
${disk_info}
磁盘使用:
${disk_use}
inode信息:
${disk_inode}
EOF
}
#---------end------------------

# 获取服务信息
function get_service_info() {
    port_listen=$(netstat -lntup|grep -v "Active Internet")
    kernel_config=$(sysctl -p 2>/dev/null)
    if [ ${sysversion} -gt 6 ];then
        service_config=$(systemctl list-unit-files --type=service --state=enabled|grep "enabled")
        run_service=$(systemctl list-units --type=service --state=running |grep ".service")
    else
        service_config=$(/sbin/chkconfig | grep -E ":on|:启用" |column -t)
        run_service=$(/sbin/service --status-all|grep -E "running")
    fi
cat <<EOF
服务启动配置:
${service_config}
${line}
运行的服务:
${run_service}
${line}
监听端口:
${port_listen}
${line}
内核参考配置:
${kernel_config}
EOF
}
#---------end------------------

#获取用户
function get_sys_user() {
    login_user=$(awk -F: '{if ($NF=="/bin/bash") print $0}' /etc/passwd)
    ssh_config=$(egrep -v "^#|^$" /etc/ssh/sshd_config)
    sudo_config=$(egrep -v "^#|^$" /etc/sudoers |grep -v "^Defaults")
    host_config=$(egrep -v "^#|^$" /etc/hosts)
    crond_config=$(for cronuser in /var/spool/cron/* ;do ls ${cronuser} 2>/dev/null|cut -d/ -f5;egrep -v "^$|^#" ${cronuser} 2>/dev/null;echo "";done)
cat <<EOF
系统登录用户:
${login_user}
${line}
ssh 配置信息:
${ssh_config}
${line}
sudo 配置用户:
${sudo_config}
${line}
定时任务配置:
${crond_config}
${line}
hosts 信息:
${host_config}
EOF
}
#---------end------------------

#获取进程信息
function process_top_info() {

    top_title=$(top -b n1|head -7|tail -1)
    cpu_top10=$(top b -n1 | head -17 | tail -11)
    mem_top10=$(top -b n1|head -17|tail -10|sort -k10 -r)

cat <<EOF
CPU占用top10:
${top_title}
${cpu_top10}
内存占用top10:
${top_title}
${mem_top10}
EOF
}
#---------end------------------
#获取检查
function sys_check() {
    get_cpu_info
    echo ${line}
    get_mem_info
    echo ${line}
    get_net_info
    echo ${line}
    get_disk_info
    echo ${line}
    get_systatus_info
    echo ${line}
    get_service_info
    echo ${line}
    get_sys_user
    echo ${line}
    process_top_info
}
#-----------end--------------------

#######
}

system_monitor() {
get_system_info
echo "
1.获取系统内存信息
2.获取系统磁盘信息
3.获取系统cpu信息
4.获取系统服务信息
5.获取系统网络信息
6.获取进程信息
7.获取用户
8.系统检查
"
while true; do


read -p "$ask " select_ask
  case $select_ask in
  1)
get_mem_info

    ;;
  2)
    get_disk_info

    ;;
  3)
get_cpu_info
    ;;
  4)
    get_service_info

    ;;
  5)
get_net_info
    ;;
  6)
process_top_info
    ;;
    7)
get_sys_user
    ;;
    8)
sys_check
    ;;
      0)


home

    ;;
  *)
    echo "$error_ask"

  esac
done
}

#调用函数
function if_root() {
  if [[ 0 == "$UID" ]]; then
    print_ok "当前用户是 root 用户，开始安装流程"
  else
    print_error "当前用户不是 root 用户，请切换到 root 用户后重新执行脚本"
    exit 1
  fi
}


system_control(){
    echo "1.防火墙管理"
    echo "2.正在开发..."
    read -p "$ask" ask_system_control
    case $ask_system_control in
    1)
      get_firewall
      ;;
     0)
     home
      ;;
    *)
      echo "$error_ask"
      home
    esac


}

get_firewall(){
  off_firewall() {
  systemctl stop firewalld&&setenforce 0&&sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config&&echo "防火墙关闭成功"||echo "防火墙关闭失败"

  }
  on_firewall() {
    echo "正在开启所有防火墙"
  systemctl start firewalld&&setenforce 1&&sed -i 's/SELINUX=enforcing/SELINUX=enforcing/g' /etc/selinux/config&&echo "防火墙开启成功"||echo "防火墙开启失败"

  }
#判断当前防火墙的状态
  if  systemctl status firewalld.service | grep "running" &>/dev/null ; then
      green "当前的防火墙状态是运行的"
      read -p "请输入1关闭|任意键返回" firewalld_Control
      case $firewalld_Control in
      1)
      off_firewall
      home
        ;;
      *)
      home
        ;;
      esac
  else
    green "防火墙是关闭的"
     read -p "请输入1开启|任意键返回" firewalld_Control
      case $firewalld_Control in
      1)
      on_firewall
      home
        ;;
      *)
      home
        ;;
      esac
  fi


}


test_network(){
    echo "正在检测当前系统网络，请等待5秒....."
  ping -c2 baidu.com &> /dev/null
if [ $? -eq 0 ] ; then
  echo "网络联通成功"
    return 0
  else
    red "无网络连接，请检查网络 如果是VMware虚拟机请将网卡修改为桥接或NAT，然后重启系统或网络"
    return 1
fi
}



get_ScriptVersion() {
      content=$(curl -L https://gitee.com/baibaibai001/shell/raw/master/version 2>/dev/null)
      last_version=$content
#      $last_version变量为最新版的版本号
	    echo "最新版本为：${last_version}"
	    echo "当前版本为：${Script_version}"
      script_install_dir=/opt/autoscript-V$last_version
}
set_ScriptPATH(){
    get_ScriptVersion & >>/dev/null
    chmod -R 777 $script_install_dir&& green "最新脚本授权成功"||red "权限授权失败,请用root用户再次检查更新"
#设置脚本的环境变量,删除老的环境变量
#    sed -i '/autoscript-V/d' /etc/profile #删除老的脚本环境变量
#    export PATH=$PATH:$script_install_dir&& green "临时设置环境变量成功"
#    echo "export PATH=$PATH:$script_install_dir" >> /etc/profile&&green "最新版本已经设置环境变量 "
#    source /etc/profile&& green "刷新环境变量配置文件成功"

#    设置命令别名，通过alias只能够在当前shell中有效，还需在终端手动执行source命令
#source /etc/profile
#        green "有jb别名 "
#        shopt -s expand_aliases
#        shopt  expand_aliases
#        alias jb="auto_shell.sh"
#        echo "alias jb='auto_shell.sh'" >> /etc/profile
#        source /etc/profile
rm -rf /usr/bin/jb
ln -s "${script_install_dir}/auto_shell.sh" /usr/bin/jb
    red "此脚本将自动退出，在终端输入 jb 即可运行最新版本"
    sleep 3;exit 0

}

 down_file() {
    get_ScriptVersion &> /dev/null #执行获取版本函数
    #获取到版本号判断更新
    if [ "$last_version" = "" ]; then
        echo "未获取到github仓库版本号"
#      -------------------判断当前版本小于获取到的git版本号，进行更新-------------------
    elif [ $Script_version -lt $last_version ]; then
           echo "有版本可以更新,正在检查git是否安装"
              if git --version -eq 0 &>/dev/null ; then #有版本可以更新，判断是否安装git工具
                echo "git已经安装"
              if [ -d $script_install_dir ]; then
                  green "最新版本已经下载在本地 $script_install_dir，无需再次更新"
                  set_ScriptPATH
                   else
                     mkdir  $script_install_dir
                      git clone $shell_address $script_install_dir
                      echo "项目已经更新到 $script_install_dir"
                      set_ScriptPATH
              fi
        else #有版本可以更新，但是没有安装git工具
            echo "git 没有安装，正在安装git"
              if yum install git* -y ; then
                  echo "git 安装成功，正在更新项目"
                      if [ -d $script_install_dir ]; then
                  echo "最新版本已经下载在本地 $script_install_dir，无需再次更新"
                  echo "请手动删除旧版本，使用 bash $script_install_dir 运行最新版本"
                  set_ScriptPATH
                   else
                     mkdir  $script_install_dir
                      git clone $shell_address $script_install_dir
                      echo "项目已经更新到 $script_install_dir"
                      echo "请手动删除旧版本，使用 bash $script_install_dir 运行最新版本"
                      set_ScriptPATH
                      fi
                  else #git没有安装成功
                    echo "error: git 安装失败，请手动安装git yum install git -y"
              fi
        fi


      else
          echo "没有版本更新 需要获取Beta版本请执行：git clone https://gitee.com/baibaibai001/shell"
    fi

  }

  check_ScriptUpdate() {
#      echo "当前版本为：${Script_version}"
      test_network
      if [ $? -eq 0 ]; then
          down_file
        else
         echo
      fi
#      content=$(curl -L https://gitee.com/baibaibai001/shell/blob/master/auto_shell.sh)
#      last_version=`grep -o -E "Script_version=(&quot;)[[:digit:]]+\1" $content | grep -o -E  "\b[[:digit:]]+\b"`
  }

 yum_config() {
#  while true; do
  echo "1.安装本地光盘源"
  echo "2.安装清华镜像源"
  read -p "$ask " select_yummode
  case $select_yummode in
  1)
    if   cat /etc/fstab  |grep "sr0" ; then
      #判断是否存在sr0 存在则sed 写入
        green "sr0是存在/etc/fstab 已将sr0设置开机挂载 -->/media/CentOS "

    else
         echo "/dev/sr0 /media/CentOS iso9660 defaults 0 0" >>/etc/fstab
         green "已将sr0设置开机挂载 -->/media/CentOS "
    fi
     green "正在配置本地光盘yum"
if df -h | grep sr0; then
  #grep找到返回值为0
   echo "/dev/sr0 是挂载的"
    umount /dev/sr0 ||fuser -mk /dev/sr0
    mount -r /dev/sr0 /media/CentOS/&&echo "光盘挂载成功 /dev/sr0 -->/media/CentOS/ "||echo "光盘挂载失败，请使用fuser 命令 "
      cd /etc/yum.repos.d/ &>/dev/null
      mkdir /etc/yum.repos.d/backup &>/dev/null
      mkdir /media/CentOS/ &>/dev/null
    mv $(ls /etc/yum.repos.d/ | grep -v CentOS-Media.repo | xargs) /etc/yum.repos.d/backup/ &>/dev/null
    echo "[local]" >/etc/yum.repos.d/CentOS-Media.repo.repo
    echo "name=local" >>/etc/yum.repos.d/CentOS-Media.repo.repo
    echo "baseurl=file:///media/CentOS" >>/etc/yum.repos.d/CentOS-Media.repo.repo
    echo "gpgcheck=0" >>/etc/yum.repos.d/CentOS-Media.repo.repo
    echo "enabled=1" >>/etc/yum.repos.d/CentOS-Media.repo.repo
    yum clean all && yum makecache&& green "本地yum配置完成,2s后自动关闭提示"&&sleep 2;clear
else
  red "光盘sr0是未挂载的"
   umount /dev/sr0 &>/dev/null ||fuser -mk /dev/sr0
      if mount -r /dev/sr0 /media/CentOS/ &>/dev/null &&echo "光盘挂载成功 /dev/sr0 -->/media/CentOS/ " ; then
          cd /etc/yum.repos.d/ &>/dev/null
          mkdir /etc/yum.repos.d/backup &>/dev/null
          mkdir /media/CentOS/ &>/dev/null
          mv $(ls /etc/yum.repos.d/ | grep -v CentOS-Media.repo | xargs) /etc/yum.repos.d/backup/ &>/dev/null
          echo "[local]" >/etc/yum.repos.d/CentOS-Media.repo.repo
          echo "name=local" >>/etc/yum.repos.d/CentOS-Media.repo.repo
          echo "baseurl=file:///media/CentOS" >>/etc/yum.repos.d/CentOS-Media.repo.repo
          echo "gpgcheck=0" >>/etc/yum.repos.d/CentOS-Media.repo.repo
          echo "enabled=1" >>/etc/yum.repos.d/CentOS-Media.repo.repo
          yum clean all && yum makecache&& green "本地yum配置完成,2s后自动关闭提示"&&sleep 2;clear
    else
            red "没有检测到 /dve/sr0设备，请在VMware右下角连接光盘"
             sleep 6
      fi

  fi
    ;;
  2)
      cd /etc/yum.repos.d/ &>/dev/null
      mkdir /etc/yum.repos.d/backup &>/dev/null
    mv $(ls /etc/yum.repos.d/ | grep -v tsinghua.repo | xargs) /etc/yum.repos.d/backup/ &>/dev/null
    cat>/etc/yum.repos.d/tsinghua.repo<<EOF
[tsinghua]
name=tsinghua
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/\$releasever/os/\$basearch/
gpgcheck=0
enabled=1
EOF

  if  ping -c 1 114.114.114.114 &> /dev/null  ;then
       yum clean all && yum makecache&& green "清华yum配置完成。" &&sleep 2;clear
else
      red "清华yum配置完成，需要连接网络使用。"
       red "如果是VMware虚拟机，请将网卡修改为桥接或nat模式，然后重启系统，确定网络可用 再执行 'yum clean all && yum makecache' 命令"
fi
    ;;
    0)
      home
    ;;

  *)
      echo "$error_ask"
    ;;
  esac

#done

  red "yum执行结束"

  home
}

yum_install_soft() {
  echo "
    1.安装ftp
    2.安装mysql
    3.开发中
    "
    if [  $UID  ==  0  ];then
         echo "环境检测完成，当前是root用户..."
else
        red "您不是管理员，没有权限安装软件 请执行 su -root"
fi
  yum_install_ftp(){
    yum install -y vsftpd-*
    systemctl restart vsftpd
    systemctl enable vsftpd
    echo "ftp启动成并设置为开机自动启动"
  }
  yum_install_mysql(){
    yum install -y mariadb-*
    systemctl restart mariadb-server
    systemctl enable mariadb-server
    echo "mysql启动成并设置为开机自动启动"
  }


read -p "$ask" ask_install
  case $ask_install in
  1)
   yum_install_ftp
   sleep 3
      clear
   yum_install_soft
    ;;
   2)
   yum_install_mysql
   sleep 3
   clear
   yum_install_soft
    ;;
    0)
   home
    ;;
  esac
}

check_firewall() {
  #检查防火墙
  if systemctl status firewalld  | grep "running" &> /dev/null  ;then
    #当为0表示防火墙是开启的状态
    firewall_status=0
    red "防火墙是开启的"
    off_firewall() {
      read -p "输入0 关闭防火墙||输入1 开启防火墙" firewalld_control
      if [ $firewalld_control -eq 0 ]; then
  sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
          setenforce 0
  systemctl stop firewalld && green "防火墙关闭成功" || red "防火墙关闭失败"
fi
    }
  else
     #当为1表示防火墙是关闭的状态
      firewall_status=1
      green "防火墙当前状态是关闭的"
    on_firewall() {
      read -p "输入0 关闭防火墙||输入1 开启防火墙" firewalld_control
      if [ $firewalld_control -eq 1 ]; then
#       sed -i 's/SELINUX=enforcing/SELINUX=enforcing/' /etc/selinux/config
#       setenforce 1
        systemctl start firewalld && green "防火墙开启成功" || red "防火墙开启失败"
      fi
    }
  fi
}

  #检查yum
    check_yum() {

  if   yum remove xeyes -q -y  &> /dev/null && yum install xeyes -q -y &> /dev/null ||yum install xeyes  -q -y &> /dev/null; then
      echo "yum可以正常使用"
       yum_status=0
      else
      red "yum配置异常,请手动配置yum"
       yum_status=1

  fi
    }
    function check_ip() {
    local IP=$1
    VALID_CHECK=$(echo $IP|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
    if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null; then
        if [ $VALID_CHECK == "yes" ]; then
         echo "IP $IP  是有效的!"
            return 0
        else
            echo "IP $IP 是无效的!"
            return 1
        fi
    else
        echo "ip地址格式错误"
        return 1
    fi
#    while true; do
#    read -p "Please enter IP: " IP
#    check_ip $IP
#    [ $? -eq 0 ] && break
#done
}


    deploy_product (){
      echo "1.自动部署dhcp"
      echo "2.自动部署dns"
      echo "3.自动部署vsftp"
      echo "4.自动部署samba"
      echo "5.自动部署lamp（开发中）"
      echo "6.自动部署rsync（开发中）"
      echo "7.自动部署tomcat（开发中）"
      echo "8.自动部署apache（开发中）"
      echo "9.自动部署nginx（开发中）"
      echo "10.一键部署docker"
    read -p "$ask" ask_deploy_product
    case $ask_deploy_product in
    1)
      install_dhcp
      ;;
    2)
      install_dns
      ;;
     3)
      install_vsftp
      ;;
    4)
      install_samba
      ;;
     5)
      install_lamp
      ;;
     6)
      install_lamp
      ;;
     7)
      install_lamp
      ;;
     8)
      install_lamp
      ;;
     9)
      install_lamp
      ;;
     10)
      install_docker
      ;;
     0)
     home
      ;;
    *)
      echo "$error_ask"
      deploy_product
    esac


    }

##自动部署dhcp
install_dhcp() {
check_firewall
check_yum
#echo $firewall_status
#echo $yum_status
if [ $firewall_status -eq 1  ]&&[ $yum_status -eq 0 ]; then
    #防火墙和yum是关闭，继续操作
#    echo "环境检查：防火墙状态：关闭的，yum状态：正常使用"
    green "注意事项：\n ① 需要关闭所有防火墙 \n ② 需要关闭 Vmware 虚拟网络编辑器的DHCP功能 \n ③ dhcp所分配的网段，必须有网卡IP在这个分配的网段，否则将启动失败"
    green "----------------------------------------------------------------"
    yum install dhcp dhcrelay dhcp-common -q -y &>>/dev/null
    read -p   "请输入需要分配的网段[usage: 192.168.19.0]:"  subnet
    read -p   "请输入需要分配的网段子网掩码[usage: 255.255.255.0]:"  netmask
    read -p   "请输入需要分配的IP范围[usage: 192.168.19.19 192.168.19.254]:" range
    read -p   "请输入需要网关[usage: 192.168.19.1]:"  gatway
    read -p   "请输入域名服务器[usage: 8.8.8.8]:" name_servers

    if test -s /etc/dhcp/dhcpd.conf ; then
        #如果文件存在并且文件大小大于0 返回真
         read -p "已经有存在的配置文件，清空还是追加配置文件（Y（清空原有配置文件）/N(追加配置文件)）" ask_dhcpd_config
        case $ask_dhcpd_config in
        y|Y)
cat>/etc/dhcp/dhcpd.conf<<EOF
subnet $subnet netmask $netmask{
  range $range;
  option domain-name "qq.com";
  option domain-name-servers $name_servers;
  option routers $gatway;
  default-lease-time 600;
  max-lease-time 7200;
}
EOF
;;
     *)
    echo "配置文件将已追加的方式写入dhcpd.conf"
    cat>>/etc/dhcp/dhcpd.conf<<EOF
subnet $subnet netmask $netmask{
  range $range;
  option domain-name "qq.com";
  option domain-name-servers $name_servers;
  option routers $gatway;
  default-lease-time 600;
  max-lease-time 7200;
}
EOF
    ;;
        esac

else
#       "配置文件不存在或为空,将以>方式写入配置文件"
            cat>/etc/dhcp/dhcpd.conf<<EOF
subnet $subnet netmask $netmask{
  range $range;
  option domain-name "qq.com";
  option domain-name-servers $name_servers;
  option routers $gatway;
  default-lease-time 600;
  max-lease-time 7200;
}
EOF

fi
green "写入配置文件 /etc/dhcp/dhcpd.conf"
systemctl restart network.service &>>/dev/null;green "重启网卡成功.."
systemctl restart dhcpd  &>>/dev/null && green "启动dhcp服务成功"||red "dhcp启动失败，或清空原有的dhcp配置文件"


  elif [ $firewall_status -eq 0 ]; then
    echo "防火墙是开启的，请关闭防火墙"
    off_firewall
    install_dhcp
  elif [ $yum_status -eq 1 ]; then
      red "请输入选项配置yum"
      yum_config

fi
}

install_dns(){
#  green "本次的版本是基于bind-V9.11.xxx"
read -p   "请输入你的zone[usage: baidu.com]:"  ZONE
while true; do
   read -p  "请输入你对应的IP地址[Usage: 192.168.0.1]:" NET
    check_ip $NET
    [ $? -eq 0 ] && break
done

#read -p  "请输入你ns1的IP地址[Usage: 192.168.0.1]:" YOURIP
#YOURIP=`ifconfig ens37| grep "inet addr" | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'`
#LAST=`echo $YOURIP | awk 'BEGIN {FS="."}{print $4}'`
#FANXIANG=`echo $NET | awk 'BEGIN {FS="."}{print $3"."$2"."$1}'`
rpm -q bind &>/dev/null
let BOOL=`echo $?`
if [ $BOOL -eq 1 ];  then
    yum -y install bind*
fi
rpm -q bind &>/dev/null
let BOOL2=`echo $?`
if [ $BOOL2 -eq 1 ]; then
  echo "bind是没有安装的，正在安装"
    yum -y install bind*
fi
#********************************************
green "正在写入 named.conf"
#直接修改文件，把匹配行的第一个127.0.0.1改为any
sed -i 's/127.0.0.1/any/' /etc/named.conf
#直接修改文件，把匹配行的第一个localhost改为any
sed -i 's/localhost/any/' /etc/named.conf
cat >>/etc/named.conf<<EOF
zone "$ZONE" IN {
        type master;
        file "$ZONE.zone";
};

EOF
#*******************************************
green "正在写入 $ZONE.zone....."
cat>/var/named/$ZONE.zone<<EOF
\$TTL 1D
@       IN SOA  @ rname.invalid. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
@       IN      NS      $ZONE.
ns1     IN      A       127.0.0.1
@       IN      A       $NET
www     IN      A       $NET
EOF

#chown :named /etc/named.conf
#chown :named /var/named/*
systemctl restart named&&systemctl enable named && echo "配置成功，named启动生效" || echo "启动失败"

#*****************************************
#nsloop -t A $ZONE
#****************************************

}
#自动部署vsftp
install_vsftp(){
      vsftpconfig() {
chown ftp /var/ftp/pub/
sed -i '/nonymous_enable=/a anon_umask=000'  /etc/vsftpd/vsftpd.conf   #匿名上传的权限掩码
sed -i 's/^#anon_upload/anon_upload/'  /etc/vsftpd/vsftpd.conf  #允许匿名上传
sed -i 's/^#anon_mkdir_/anon_mkdir_/'  /etc/vsftpd/vsftpd.conf  #匿名访问时允许创建子目录
sed -i '/^anon_mkdir_/a anon_other_write_enable=YES'  /etc/vsftpd/vsftpd.conf #允许匿名访问时
systemctl start vsftpd&&systemctl enable vsftpd && echo "vsftp启动成功 允许匿名访问" ||echo "vsftp失败的，请手动配置"
      }
  if rpm -qa |grep "vsftpd"; then
      echo "vsftpd已经安装"
      vsftpconfig
  else
     echo "vsftpd正在安装"
     yum install vsftpd -y
     vsftpconfig
  fi

}
install_samba(){
  green "
  1.协议：SMB/CIFS
  2.服务：smb	实现资源共享、权限验证、TCP 139 445
  3.配置文件：/etc/samba/smb.conf
  "
  smaba_config() {
    read -p  "请输入你共享的名称(唯一):" samba
    read -p  "请输入你共享描述:" samba_comment
    read -p  "请输入对该共享的绝对路径(usage:/opt/share):" share_path
    read -p  "请输入对该共享授权的用户名:" samba_user

   cat>>/etc/samba/smb.conf<<EOF
[$samba]
        comment=$samba_comment
        path=$share_path
        valid user=$samba_user
        browseable=yes
        writeable=yes
        public=yes
EOF

useradd $samba_user
pdbedit -a -u $samba_user
mkdir "$share_path" && echo "$share_path 目录创建成功"|| echo " 更新目录 $path 创建失败"
echo $samba_user
echo $samba_user
echo $share_path
chown $samba_user:$samba_user $share_path
green "修改配置文件完成 配置文件/etc/samba/smb.conf "
systemctl restart nmb smb && green "samba相关服务启动成功"||red "samba 启动失败，请手动检查配置文件"
}

#判断有相同的文件
#if [ cat ]; then
#
#fi
  if  rpm -q samba &>>/dev/null ; then
      #已经安装
          smaba_config
      echo
   else
     echo "正在安装samba"
     yum -y install samba;	rpm -q samba-client ; rpm -q samba-common
    smaba_config
  fi
}

#安装docker
install_docker() {
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
# step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: 添加软件源信息
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3
sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
# Step 4: 更新并安装Docker-CE
sudo yum makecache fast
sudo yum -y install docker-ce
# Step 4: 开启Docker服务
sudo service docker start && green "安装docker成功" ||red "安装docker失败"
# 注意：
# 官方软件源默认启用了最新的软件，您可以通过编辑软件源的方式获取各个版本的软件包。例如官方并没有将测试版本的软件源置为可用，您可以通过以下方式开启。同理可以开启各种测试版本等。
# vim /etc/yum.repos.d/docker-ce.repo
#   将[docker-ce-test]下方的enabled=0修改为enabled=1
#
# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# yum list docker-ce.x86_64 --showduplicates | sort -r
#   Loading mirror speeds from cached hostfile
#   Loaded plugins: branch, fastestmirror, langpacks
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            docker-ce-stable
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            @docker-ce-stable
#   docker-ce.x86_64            17.03.0.ce-1.el7.centos            docker-ce-stable
#   Available Packages
# Step2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.0.ce.1-1.el7.centos)
# sudo yum -y install docker-ce-[VERSION]
#----------------------------------
}


#---------------------------------------------------
 home () {

    clear

    echo -e "\033[32m==============================================\033[0m"
    echo "wlcome $USER " $(date)
    echo "$var1"
    echo "$var2"
    echo "$var3"
    echo "$var4"
    echo "$var5"

    red "$var99"
    echo -e "\033[32m==============================================\033[0m"
    read -p "请输入你需要选择的功能[1-99]" num
    case "$num" in
    1)
    yum_config
    ;;
    2)
    system_monitor
    ;;
    3)
    yum_install_soft
    ;;
    4)
    system_control
    ;;
    5)
    deploy_product
    ;;
    99)
    check_ScriptUpdate
    sleep 4s
    home
    ;;
    0)
    home

    ;;

    exit|EXIT|quit|QUIT|q|e|Q)
    exit 0
    ;;
    *)
    clear
    red "请输入正确数字，ctrl+c退出"
    sleep 0.5s
    home
    ;;
    esac
}
home